package com.rongmei.jdsync.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rongmei.jdsync.dto.*;
import com.rongmei.jdsync.entity.Category;
import com.rongmei.jdsync.entity.GoodsDetail;
import com.rongmei.jdsync.entity.Label;
import com.rongmei.jdsync.entity.SkuData;
import com.rongmei.jdsync.repository.*;
import com.rongmei.jdsync.service.JdCategorySyncService;
import com.rongmei.jdsync.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 京东商品分类同步服务实现类
 *
 * @author dongjun
 */
@Slf4j
@Service
public class JdCategorySyncServiceImpl implements JdCategorySyncService {
    private final CategoryRepository categoryRepository;

    private final LabelRepository labelRepository;

    private final GoodsRepository goodsRepository;
    private final GoodsDetailRepository goodsDetailRepository;

    private final SkuDataRepository skuDataRepository;


    /**
     * JdCategorySyncServiceImpl类的构造方法
     *
     * @param categoryRepository 分类信息仓库
     * @param labelRepository    标签信息仓库
     * @param goodsRepository    商品信息仓库
     * @param goodsDetailRepository 商品详细信息仓库
     * @param skuDataRepository  SKU数据仓库
     */
    public JdCategorySyncServiceImpl(
            CategoryRepository categoryRepository,
            LabelRepository labelRepository,
            GoodsRepository goodsRepository,
            GoodsDetailRepository goodsDetailRepository, SkuDataRepository skuDataRepository) {
        this.categoryRepository = categoryRepository;
        this.labelRepository = labelRepository;
        this.goodsRepository = goodsRepository;
        this.goodsDetailRepository = goodsDetailRepository;
        this.skuDataRepository = skuDataRepository;
    }


    // 使用ThreadLocal来存储计数器
    private final ThreadLocal<Integer> categorySaveCounter = ThreadLocal.withInitial(() -> 0);

    @Value("${jd.api.url}")
    private String jdApiUrl;

    @Value("${jd.api.auth}")
    private String jdApiAuth;

    @Value("${jd.api.label.url}")
    private String jdLabelApiUrl;

    @Value("${jd.api.goods.url}")
    private String jdGoodsApiUrl;
    @Value("${jd.api.goods.detail.url}")
    private String jdGoodsDetailUrl;

    /**
     * 保存分类信息
     *
     * @param responseDto 包含分类信息的响应对象
     * @return 操作结果，返回1表示操作成功
     */
    @Override
    @Transactional
    public int saveCategories(JdCategoryResponseDto responseDto) {
        long startTime = System.currentTimeMillis();
        int totalCount = 0;

        try {
            log.info("开始保存京东商品分类数据");

            if (responseDto == null || responseDto.getData() == null) {
                log.warn("接收到空的分类数据");
                return 0;
            }

            // 使用ThreadLocal来存储计数器
            ThreadLocal<Integer> counter = ThreadLocal.withInitial(() -> 0);

            try {
                saveCategories(responseDto.getData());
                totalCount = counter.get();

                log.info("商品分类数据保存完成，共保存 {} 个分类，耗时 {} ms", totalCount, System.currentTimeMillis() - startTime);

                return totalCount;
            } finally {
                counter.remove(); // 清理ThreadLocal
            }
        } catch (Exception e) {
            log.error("保存商品分类数据时发生错误: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 同步京东商品分类
     *
     * @param categoryName 需要同步的商品分类名称
     * @return 同步结果，包含同步的商品分类信息
     * @throws IOException 当发生IO异常时抛出
     */
    @Override
    @Transactional
    public JdCategoryResponseDto syncCategories(String categoryName) throws IOException {
        long startTime = System.currentTimeMillis();
        log.info("开始同步京东商品分类数据，分类名称: {}", categoryName != null ? categoryName : "全部");

        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("category_name", categoryName != null ? categoryName : "").build();

        Request request = HttpClientUtil.buildRequest(jdApiUrl, jdApiAuth, body);

        try {
            Response response = HttpClientUtil.createHttpClient().newCall(request).execute();
            JdCategoryResponseDto result = HttpClientUtil.processResponse(response, JdCategoryResponseDto.class);

            int dataSize = result.getData() != null ? result.getData().size() : 0;
            HttpClientUtil.logRequestCompletion("京东分类数据获取", dataSize, startTime);

            ThreadLocal<Integer> counter = ThreadLocal.withInitial(() -> 0);
            try {
                if (result.getData() != null) {
                    saveCategories(result.getData());
                }
                HttpClientUtil.logRequestCompletion("京东商品分类同步", counter.get(), startTime);
                return result;
            } finally {
                counter.remove();
            }
        } catch (IOException e) {
            log.error("同步京东商品分类数据时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 保存商品分类数据到数据库
     *
     * @param data 包含商品分类数据的列表
     */
    private void saveCategories(List<JdCategoryDataDto> data) {
        if (data == null || data.isEmpty()) {
            log.debug("收到空的一级分类列表，跳过处理");
            return;
        }

        log.info("开始处理 {} 个一级分类", data.size());

        for (JdCategoryDataDto datum : data) {
            try {
                Category category = new Category();
                category.setCategoryId(datum.getCategory_id());
                category.setCategoryId1(datum.getCategory_id_1());
                category.setCategoryId2(datum.getCategory_id_2());
                category.setCategoryId3(datum.getCategory_id_3());
                category.setCategoryName(datum.getCategory_name());
                category.setImage(datum.getImage());
                category.setImageAdv(datum.getImage_adv());
                category.setLevel((int) datum.getLevel());
                category.setPid(datum.getPid());
                category.setShortName(datum.getShort_name());

                categoryRepository.save(category);
                categorySaveCounter.set(categorySaveCounter.get() + 1);

                log.debug("成功保存一级分类: {}, ID: {}", category.getCategoryName(), category.getCategoryId());

                if (datum.getChild_list() != null && !datum.getChild_list().isEmpty()) {
                    log.debug("处理一级分类 {} 的 {} 个子分类", category.getCategoryName(), datum.getChild_list().size());
                    saveChildCategories(datum.getChild_list(), datum.getCategory_id());
                }
            } catch (Exception e) {
                log.error("保存一级分类 {} 时发生错误: {}", datum.getCategory_name(), e.getMessage(), e);
                throw e;
            }
        }
    }

    /**
     * 保存子分类信息
     *
     * @param childList 子分类列表
     * @param parentId  父分类ID
     */
    private void saveChildCategories(List<JdCategoryChildNodeDto> childList, Long parentId) {
        if (childList == null || childList.isEmpty()) {
            log.debug("收到空的二级分类列表，跳过处理");
            return;
        }

        log.debug("开始处理 {} 个二级分类", childList.size());
        List<Category> categories = new ArrayList<>();

        for (JdCategoryChildNodeDto child : childList) {
            try {
                Category category = new Category();
                category.setCategoryId(child.getCategory_id());
                category.setCategoryId1(child.getCategory_id_1());
                category.setCategoryId2(child.getCategory_id_2());
                category.setCategoryId3(child.getCategory_id_3());
                category.setCategoryName(child.getCategory_name());
                category.setImage(child.getImage());
                category.setImageAdv(child.getImage_adv());
                category.setLevel((int) child.getLevel());
                category.setPid(parentId);
                category.setShortName(child.getShort_name());

                categories.add(category);
                categorySaveCounter.set(categorySaveCounter.get() + 1);

                log.debug("准备保存二级分类: {}, ID: {}", category.getCategoryName(), category.getCategoryId());

                if (child.getChild_list() != null && !child.getChild_list().isEmpty()) {
                    log.debug("处理二级分类 {} 的 {} 个子分类", category.getCategoryName(), child.getChild_list().size());
                    saveGrandChildCategories(child.getChild_list(), child.getCategory_id());
                }
            } catch (Exception e) {
                log.error("处理二级分类 {} 时发生错误: {}", child.getCategory_name(), e.getMessage(), e);
                throw e;
            }
        }

        if (!categories.isEmpty()) {
            categoryRepository.saveAll(categories);
            log.debug("成功批量保存 {} 个二级分类", categories.size());
        }
    }

    /**
     * 保存三级子分类
     *
     * @param grandChildList 三级子分类列表
     * @param parentId       父分类ID
     */
    private void saveGrandChildCategories(List<JdCategoryChildDto> grandChildList, Long parentId) {
        if (grandChildList == null || grandChildList.isEmpty()) {
            log.debug("收到空的三级分类列表，跳过处理");
            return;
        }

        log.debug("开始处理 {} 个三级分类", grandChildList.size());
        List<Category> categories = new ArrayList<>();

        for (JdCategoryChildDto grandChild : grandChildList) {
            try {
                Category category = new Category();
                category.setCategoryId(grandChild.getCategory_id());
                category.setCategoryId1(grandChild.getCategory_id_1());
                category.setCategoryId2(grandChild.getCategory_id_2());
                category.setCategoryId3(grandChild.getCategory_id_3());
                category.setCategoryName(grandChild.getCategory_name());
                category.setImage(grandChild.getImage());
                category.setImageAdv(grandChild.getImage_adv());
                category.setLevel((int) grandChild.getLevel());
                category.setPid(parentId);
                category.setShortName(grandChild.getShort_name());

                categories.add(category);
                categorySaveCounter.set(categorySaveCounter.get() + 1);

                log.debug("准备保存三级分类: {}, ID: {}", category.getCategoryName(), category.getCategoryId());
            } catch (Exception e) {
                log.error("处理三级分类 {} 时发生错误: {}", grandChild.getCategory_name(), e.getMessage(), e);
                throw e;
            }
        }

        if (!categories.isEmpty()) {
            categoryRepository.saveAll(categories);
            log.debug("成功批量保存 {} 个三级分类", categories.size());
        }
    }

    @Override
    public JdLabelResponseDto getLabelList() throws IOException {
        long startTime = System.currentTimeMillis();
        log.info("开始获取京东商品分组数据");

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, "{}");
        Request request = HttpClientUtil.buildRequest(jdLabelApiUrl, jdApiAuth, body);

        try {
            Response response = HttpClientUtil.createHttpClient().newCall(request).execute();
            JdLabelResponseDto result = HttpClientUtil.processResponse(response, JdLabelResponseDto.class);

            int dataSize = result.getData() != null ? result.getData().size() : 0;
            HttpClientUtil.logRequestCompletion("京东商品分组数据获取", dataSize, startTime);
            return result;
        } catch (IOException e) {
            log.error("获取京东商品分组数据时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 保存京东商品分组数据
     *
     * @param responseDto 京东商品分组数据响应对象
     * @return 保存的商品分组总数
     */
    @Override
    @Transactional
    public int saveLabelList(JdLabelResponseDto responseDto) {
        if (responseDto == null || responseDto.getData() == null) {
            log.warn("保存京东商品分组数据时，响应对象为空或数据列表为空");
            return 0;
        }
        try {
            List<JdLabelDataDto> jdLabelDataDtos = responseDto.getData();
            if (jdLabelDataDtos.isEmpty()) {
                log.warn("保存京东商品分组数据时，数据列表为空");
                return 0;
            }
            log.info("开始保存 {} 个京东商品分组", jdLabelDataDtos.size());
            List<Label> labels = jdLabelDataDtos.stream().map(dto -> {
                Label label = new Label();
                label.setLabelId(dto.getId());
                label.setLabelName(dto.getLabel_name());
                label.setSort(dto.getSort());
                label.setSiteId(dto.getSite_id());
                return label;
            }).collect(Collectors.toList());

            int totalSaved = labelRepository.saveAll(labels).size();
            log.info("成功保存 {} 个京东商品分组", totalSaved);
            return totalSaved;
        } catch (Exception e) {
            return 1;
        }
    }

    /**
     * 获取京东商品列表
     *
     * @param requestDto 请求参数
     * @return JdGoodsResponseDto 商品列表响应对象
     */
    @Override
    public JdGoodsResponseDto getGoodsList(GoodsRequestDto requestDto) {
        long startTime = System.currentTimeMillis();
        log.info("开始获取京东商品列表数据");

        RequestBody body = buildRequestBody(requestDto);
        Request request = HttpClientUtil.buildRequest(jdGoodsApiUrl, jdApiAuth, body);

        try {
            Response response = HttpClientUtil.createHttpClient().newCall(request).execute();
            JdGoodsResponseDto result = HttpClientUtil.processResponse(response, JdGoodsResponseDto.class);

            HttpClientUtil.logRequestCompletion("京东商品列表数据获取",
                result.getData() != null ? result.getData().getList().size() : 0,
                startTime);
            saveGoodsList(result);
            return result;
        } catch (IOException e) {
            log.error("获取京东商品列表数据时发生异常: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 构建请求体
     *
     * @param requestDto 商品请求参数
     * @return 构建完成的请求体对象
     */
    private RequestBody buildRequestBody(GoodsRequestDto requestDto) {
        // 设置请求体类型
        MediaType mediaType = MediaType.parse("text/plain");
        return new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("page", requestDto.getPage().toString())
                .addFormDataPart("limit", requestDto.getLimit().toString())
                .addFormDataPart("keyword", requestDto.getKeyword() != null ? requestDto.getKeyword() : "")
                .addFormDataPart("category_id",
                        requestDto.getCategoryId() != null ? requestDto.getCategoryId().toString() : "")
                .addFormDataPart("min_price",
                        requestDto.getMinPrice() != null ? requestDto.getMinPrice().toString() : "")
                .addFormDataPart("max_price",
                        requestDto.getMaxPrice() != null ? requestDto.getMaxPrice().toString() : "")
                .addFormDataPart("is_free_shipping",
                        requestDto.getIsFreeShipping() != null ? requestDto.getIsFreeShipping().toString() : "")
                .addFormDataPart("order", requestDto.getOrder() != null ? requestDto.getOrder() : "complex")
                .addFormDataPart("sort", requestDto.getSort() != null ? requestDto.getSort() : "desc")
                .addFormDataPart("coupon", requestDto.getCoupon() != null ? requestDto.getCoupon() : "")
                .addFormDataPart("brand_id", requestDto.getBrandId() != null ? requestDto.getBrandId().toString() : "")
                .addFormDataPart("site_id", requestDto.getSiteId() != null ? requestDto.getSiteId().toString() : "")
                .addFormDataPart("label_id", requestDto.getLabelId() != null ? requestDto.getLabelId().toString() : "")
                .addFormDataPart("goods_type",
                        requestDto.getGoodsType() != null ? requestDto.getGoodsType().toString() : "")
                .addFormDataPart("longitude",
                        requestDto.getLongitude() != null ? requestDto.getLongitude().toString() : "")
                .addFormDataPart("latitude",
                        requestDto.getLatitude() != null ? requestDto.getLatitude().toString() : "")
                .addFormDataPart("other", requestDto.getOther() != null ? requestDto.getOther().toString() : "1")
                .build();
    }

    /**
     * 执行HTTP请求并处理响应
     *
     * @param client OkHttp客户端实例
     * @param request 请求对象
     * @param startTime 请求开始时间戳
     * @return 商品列表响应对象
     * @throws IOException 如果发生IO异常或响应失败
     */
    private JdGoodsResponseDto executeRequestAndProcess(OkHttpClient client, Request request, long startTime) throws IOException {
        // 发送请求并获取响应
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            // 获取响应体内容
            String responseBody = response.body().string();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 解析响应体为 JdGoodsResponseDto 对象
                JdGoodsResponseDto result = objectMapper.readValue(responseBody, JdGoodsResponseDto.class);
                log.info("获取京东商品列表数据完成，共 {} 条数据，耗时 {} ms",
                        result.getData() != null ? result.getData().getList().size() : 0,
                        System.currentTimeMillis() - startTime);
                // 保存商品列表
                this.saveGoodsList(result);
                return result;
            } catch (JsonProcessingException e) {
                // 捕获 JSON 解析异常
                log.error("JSON解析失败: {}", e.getMessage(), e);
                throw new IOException("JSON解析失败: " + e.getMessage());
            }
        } else {
            // 捕获响应失败的情况
            log.error("获取商品列表失败: {} - {}", response.code(), response.message());
            throw new IOException("获取商品列表失败: " + response.code() + " - " + response.message());
        }
    }


    /**
     * 获取商品详情信息
     *
     * @param goodsId    商品ID
     * @param provinceId 省份ID（可选）
     * @param cityId     城市ID（可选）
     * @return 商品详情信息响应数据
     * @throws IOException 当API调用失败时抛出
     */
    @Override
    public GoodsDetailInfoResponseDto getGoodsDetailInfo(String goodsId, String provinceId, String cityId)
            throws IOException {
        long startTime = System.currentTimeMillis();
        log.info("开始获取商品详情信息，商品ID: {}", goodsId);

        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("goods_id", goodsId)
                .addFormDataPart("province_id", provinceId == null ? "" : provinceId)
                .addFormDataPart("city_id", cityId == null ? "" : cityId)
                .build();

        Request request = HttpClientUtil.buildRequest(jdGoodsDetailUrl, jdApiAuth, body);

        try {
            Response response = HttpClientUtil.createHttpClient().newCall(request).execute();
            GoodsDetailInfoResponseDto result = HttpClientUtil.processResponse(response, GoodsDetailInfoResponseDto.class);
            HttpClientUtil.logRequestCompletion("商品详情信息获取", 1, startTime);
            return result;
        } catch (IOException e) {
            log.error("获取商品详情信息时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 保存商品详情信息
     *
     * @param goodsDetailDto 商品详情DTO
     */
    @Override
    @Transactional
    public void saveGoodsDetail(GoodsDetailDto goodsDetailDto) {
        if (goodsDetailDto == null) {
            log.warn("保存商品详情时，传入的DTO对象为空");
            return;
        }
        log.info("开始保存商品详情，商品ID: {}", goodsDetailDto.getGoodsId());
        try {
            // 1. 保存商品详情基本信息
            GoodsDetail goodsDetail = convertDtoToGoodsDetail(goodsDetailDto);
            goodsDetail = goodsDetailRepository.save(goodsDetail);
            // 3. 保存SKU数据
            saveSkuDataList(goodsDetailDto, goodsDetailDto.getSkuData());
            log.info("商品详情保存成功，商品ID: {}", goodsDetail.getGoodsId());
        } catch (Exception e) {
            log.error("保存商品详情时发生错误，商品ID: {}, 错误信息: {}", goodsDetailDto.getGoodsId(), e.getMessage(), e);
            throw new RuntimeException("保存商品详情失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将GoodsDetailDto转换为GoodsDetail实体
     *
     * @param goodsDetailDto 商品详情DTO对象
     * @return GoodsDetail 商品详情实体
     */
    private GoodsDetail convertDtoToGoodsDetail(GoodsDetailDto goodsDetailDto) {
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId(Math.toIntExact(goodsDetailDto.getGoodsId()));
        goodsDetail.setBrandId(Math.toIntExact(goodsDetailDto.getBrandId()));
        goodsDetail.setBrandLogo(goodsDetailDto.getBrandLogo());
        goodsDetail.setBrandName(goodsDetailDto.getBrandName());
        goodsDetail.setCategoryId(goodsDetailDto.getCategoryId());
        goodsDetail.setCostPrice(goodsDetailDto.getCostPrice());
        goodsDetail.setDeliveryType(goodsDetailDto.getDeliveryType());
        goodsDetail.setGoodsImage(goodsDetailDto.getGoodsImage());
        goodsDetail.setGoodsName(goodsDetailDto.getGoodsName());
        goodsDetail.setGoodsServiceIds(goodsDetailDto.getGoodsServiceIds());
        goodsDetail.setGoodsSource(goodsDetailDto.getGoodsSource());
        goodsDetail.setGoodsState(goodsDetailDto.getGoodsState());
        goodsDetail.setGoodsStock(goodsDetailDto.getGoodsStock());
        goodsDetail.setGoodsType(goodsDetailDto.getGoodsType());
        goodsDetail.setIntroduction(goodsDetailDto.getIntroduction());
        goodsDetail.setIsCollect(goodsDetailDto.getIsCollect());
        goodsDetail.setIsMakeupsGoods(goodsDetailDto.getIsMakeupsGoods());
        goodsDetail.setIsSku(goodsDetailDto.getIsSku());
        goodsDetail.setIsVip(goodsDetailDto.getIsVip());
        goodsDetail.setLatitude(goodsDetailDto.getLatitude());
        goodsDetail.setLongitude(goodsDetailDto.getLongitude());
        goodsDetail.setMainImage(goodsDetailDto.getMainImage());
        goodsDetail.setMarketPrice(goodsDetailDto.getMarketPrice());
        goodsDetail.setPrice(goodsDetailDto.getPrice());
        goodsDetail.setProfitRatio(goodsDetailDto.getProfitRatio());
        goodsDetail.setPromotionAddon(goodsDetailDto.getPromotionAddon());
        goodsDetail.setSaleNum(goodsDetailDto.getSaleNum());
        goodsDetail.setServicePhone(goodsDetailDto.getServicePhone());
        goodsDetail.setSiteId(goodsDetailDto.getSiteId());
        goodsDetail.setSkuId(goodsDetailDto.getSkuId());
        goodsDetail.setSource(goodsDetailDto.getSource());
        goodsDetail.setStartSaleTime(goodsDetailDto.getStartSaleTime());
        goodsDetail.setUnit(goodsDetailDto.getUnit());
        goodsDetail.setVideoUrl(goodsDetailDto.getVideoUrl());
        goodsDetail.setVipPrice(goodsDetailDto.getVipPrice());
        return goodsDetail;
    }

    /**
     * 保存SKU数据列表
     *
     * @param goodsDetailDto 商品详情DTO对象
     * @param skuDtoList SKU DTO列表
     */
    private void saveSkuDataList(GoodsDetailDto goodsDetailDto, List<SkuDataDto> skuDtoList) {
        if (skuDtoList == null) return;

        List<SkuData> skuDataList = skuDtoList.stream()
                .map(skuDto -> {
                    SkuData skuData = new SkuData();
                    skuData.setGoodsId(goodsDetailDto.getGoodsId());
                    skuData.setSkuId(skuDto.getSkuId());
                    skuData.setSkuName(skuDto.getSkuName());
                    skuData.setSkuImage(skuDto.getSkuImage());
                    skuData.setPrice(skuDto.getPrice());
                    skuData.setMarketPrice(skuDto.getMarketPrice());
                    skuData.setCostPrice(skuDto.getCostPrice());
                    skuData.setStock(skuDto.getStock());
                    skuData.setWeight(skuDto.getWeight());
                    skuData.setVolume(skuDto.getVolume());
                    skuData.setGoodsState(1);
                    return skuData;
                })
                .collect(Collectors.toList());
        skuDataRepository.saveAll(skuDataList);
    }





    private void saveGoodsList(JdGoodsResponseDto response) {
        if (response == null || response.getData() == null) {
            log.warn("保存京东商品列表数据时，响应对象为空或数据列表为空");
            return;
        }
        try {

            log.info("开始保存 {} 个京东商品", response.getData().getList().size());
            int totalSaved = goodsRepository.saveAll(response.getData().getList()).size();
            log.info("成功保存 {} 京东商品列表数据时", totalSaved);

        } catch (Exception e) {
            log.error("保存京东商品列表数据时发生异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 根据类别的categoryId获取类别信息
     *
     * @param categoryId 类别ID
     * @return 类别信息列表
     */
    @Override
    public List<com.rongmei.jdsync.entity.Category> getCategoryList(Long categoryId) {
        log.info("获取分类ID为 {} 的子分类列表", categoryId);

        try {
            if (categoryId == null) {
                // 如果categoryId为空，则返回所有一级分类
                log.info("categoryId为空，返回所有一级分类");
                return categoryRepository.findByPidIsNull();
            } else {
                // 返回指定分类ID的子分类
                log.info("返回分类ID {} 的子分类列表", categoryId);
                return categoryRepository.findByPid(categoryId);
            }
        } catch (Exception e) {
            log.error("获取分类列表时发生错误: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}